package com.tonggedata.dataapi.gateway;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;


/**
 * apisix交互
 *
 * @author tonggedata
 * @date 2022-6-26 09:23:23
 */
@Component
public class ApiGateWay {
    private static final Logger logger = LoggerFactory.getLogger(ApiGateWay.class);


    @Autowired
    private RestTemplate restTemplate;

    @Value("${apisix.api.url}")
    private String apiUrl;
    @Value("${apisix.api.key}")
    private String apiKey;

    private String upStreamsUrl;
    private String routesUrl;
    private String consumersUrl;

    @PostConstruct
    private void init() {
        this.upStreamsUrl = apiUrl + "/upstreams";
        this.routesUrl = apiUrl + "/routes";
        this.consumersUrl = apiUrl + "/consumers";
    }


    public void createUpStream() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("retries",1);
        JSONObject timeoutJson = new JSONObject();
        timeoutJson.put("connect",15);
        timeoutJson.put("send",15);
        timeoutJson.put("read",15);
        jsonObject.put("timeout", timeoutJson);

        JSONObject nodesJson = new JSONObject();
        nodesJson.put("httpbin.org:80", 100);
        jsonObject.put("nodes",nodesJson);
        jsonObject.put("type","roundrobin");
        jsonObject.put("key","");
        jsonObject.put("name","测试");
        jsonObject.put("desc","");
        jsonObject.put("scheme","http");
        ResponseEntity<String> restR = restTemplate.postForEntity(upStreamsUrl, jsonObject, String.class);
        logger.info("restR {}", restR);
    }

    public void createRoute(Long id, String upStreamId, String path, String method) {
        JSONObject jsonObject = new JSONObject();
        JSONArray urisArray = new JSONArray();
        urisArray.put(path);
        jsonObject.put("uris",urisArray);
        JSONArray methodsArray = new JSONArray();
        methodsArray.put(method);

        JSONObject timeoutJson = new JSONObject();
        timeoutJson.put("connect",15);
        timeoutJson.put("send",15);
        timeoutJson.put("read",15);
        jsonObject.put("timeout", timeoutJson);

        JSONArray hosts = new JSONArray();
        hosts.put("httpbin.org");

        jsonObject.put("hosts",hosts);
        jsonObject.put("name","测试API");
        jsonObject.put("desc","");
        jsonObject.put("upstream_id",upStreamId);
        String routeIdStr = routesUrl + "/" + id;
        restTemplate.put(routeIdStr, jsonObject, String.class);
        logger.info("createRoute success ");
    }

    public void createConsumer(Long id, String userName) {
        JSONObject jsonObject = new JSONObject();
        JSONObject pluginsJson = new JSONObject();
        pluginsJson.put("key-auth", getKeyAuthPlugin());
        jsonObject.put("plugins", pluginsJson);
        jsonObject.put("username", userName);
        jsonObject.put("desc", "desc");
        String routeIdStr = routesUrl + "/" + id;
        restTemplate.put(routeIdStr, jsonObject, String.class);
        logger.info("createRoute success ");
    }

    public void enablePlugin(Long id, String upStreamId, String path, String method) {
        JSONObject jsonObject = new JSONObject();
        JSONObject pluginsJson = new JSONObject();
        pluginsJson.put("key-auth", getKeyAuthPlugin());
        pluginsJson.put("limit-count", getLimitCountPlugin());
        jsonObject.put("plugins", pluginsJson);
        String routeIdStr = routesUrl + "/" + id;
        restTemplate.patchForObject(routeIdStr, jsonObject, String.class);
        logger.info("createRoute success ");
    }

    public JSONObject getKeyAuthPlugin(){
        JSONObject pluginsJson = new JSONObject();
        pluginsJson.put("key","auth-one");
        return pluginsJson;
    }

    public JSONObject getJwtAuthPlugin(){
        JSONObject pluginsJson = new JSONObject();
        pluginsJson.put("key","user-key");
        pluginsJson.put("secret","my-secret-key");
        return pluginsJson;
    }

    public JSONObject getLimitCountPlugin(){
        JSONObject pluginsJson = new JSONObject();
        pluginsJson.put("count",2);
        pluginsJson.put("time_window",60);
        pluginsJson.put("rejected_code",503);
        pluginsJson.put("key","remote_addr");
        return pluginsJson;
    }

    public void updateRoute(Long id, String path, String method) {
        JSONObject jsonObject = new JSONObject();
        JSONArray urisArray = new JSONArray();
        urisArray.put(path);
        jsonObject.put("uris",urisArray);
        JSONArray methodsArray = new JSONArray();
        methodsArray.put(method);

        JSONObject timeoutJson = new JSONObject();
        timeoutJson.put("connect",15);
        timeoutJson.put("send",15);
        timeoutJson.put("read",15);
        jsonObject.put("timeout", timeoutJson);

        jsonObject.put("name","测试API");
        jsonObject.put("desc","");
        String routeIdStr = routesUrl + "/" + id;
        restTemplate.patchForObject(routeIdStr, jsonObject, String.class);
        logger.info("createRoute success ");
    }

    /**
     * "status": 0 offline
     * "status": 1  online
     *
     * @param status
     */
    public String changeRouteStatus(Long id, Integer status) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", status);
        String routeIdUrl = routesUrl + "/" + id;
        String restR = restTemplate.patchForObject(routeIdUrl, jsonObject, String.class);
        logger.info(restR);
        return restR;
    }


}
